<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    img {
        width: 220px;
        display: block;
    }   
    .item {
        box-shadow: 2px 2px 2px #999;
        position: absolute;
        padding: 10px;
    }
    #box{
      position: relative;
    }
</style>

<div id="box">
   
</div>
<script type="text/javascript">

	var max=document.getElementById("box");
	var items=max.children;
	window.onload=function(){
		render(data);
		waterFall();
		 window.onresize = function() {
            waterFall();
        };

	}
	var gap = 10;
    var data=[
    "img/0.jpg",
    "img/1.jpg",
    "img/2.jpg",
    "img/3.jpg",
    "img/4.jpg",
    "img/5.jpg",
    "img/6.jpg",
    "img/7.jpg",
    "img/8.jpg",
    "img/9.jpg",
    "img/10.jpg",
    "img/11.jpg",
    "img/12.jpg",
    "img/13.jpg",
    "img/14.jpg",
    "img/15.jpg"
    ]
	function render(data){
		data.map((i)=>{
			var div=document.createElement("div");
			div.className="item";
			div.innerHTML="<img src=" + i +">";
			max.appendChild(div)
		})
	}

	function waterFall(){
		var pageWidth=getWidth();
		var itemWidth=items[0].offsetWidth;
		var columns=parseInt(pageWidth/(itemWidth+gap));
		max.style.width=columns*(itemWidth+gap)-gap;
		max.style.margin="0 auto";
		var colArr=[]//存储每一列总高度;
		for(var i=0;i<items.length;i++){
			if(i<columns){
				items[i].style.top=0;
				items[i].style.left=(itemWidth+gap)*i+"px";
				colArr.push(items[i].offsetHeight);
			}
			else{
				var minColHeight=colArr[0];
				var minColIndex=0;
				for(j=0;i<colArr.length;j++){
					if(minColHeight>colArr[j]){
						minColHeight=colArr[j];
						minColIndex=j;
					}
				}
				items[i].style.top=colArr[minColIndex]+gap+"px";
				items[i].style.left=(itemWidth+gap)*minColIndex+"px";
				colArr[minColIndex]+=items[i].offsetHeight+gap;
			}
		}
	}

	function getWidth(){
		return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
	}
</script>
</html>